const Controller = require('egg').Controller;

class ChatController extends Controller {
  // 发送消息
  async sendMessage() {
    const { ctx, app } = this;
    const { socket } = ctx;
    const message = ctx.args[0];

    try {
      // 验证消息数据
      if (!message || !message.receiver_id || !message.content) {
        socket.emit('error', { msg: '消息数据不完整' });
        return;
      }

      // 构造消息数据
      const messageData = {
        sender_id: socket.userId,
        receiver_id: parseInt(message.receiver_id),
        content: message.content,
        message_type: message.message_type || 'text',
        image_url: message.image_url || null,
        file_url: message.file_url || null,
      };

      // 保存消息到数据库
      const savedMessage = await ctx.service.message.sendMessage(messageData);

      // 发送给发送者(确认)
      socket.emit('messageSent', {
        code: 0,
        data: savedMessage,
        msg: '发送成功'
      });

      // 推送给接收者
      const receiverSocket = app.io.userSockets.get(messageData.receiver_id);
      if (receiverSocket) {
        receiverSocket.emit('newMessage', {
          code: 0,
          data: savedMessage,
          msg: '收到新消息'
        });
        console.log(`消息已推送给用户 ${messageData.receiver_id}`);
      } else {
        console.log(`用户 ${messageData.receiver_id} 不在线,消息已保存`);
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      socket.emit('error', {
        msg: error.message || '发送消息失败'
      });
    }
  }

  // 加入会话房间
  async joinConversation() {
    const { ctx } = this;
    const { socket } = ctx;
    const { conversation_id } = ctx.args[0] || {};

    try {
      if (!conversation_id) {
        socket.emit('error', { msg: '会话ID不能为空' });
        return;
      }

      // 加入房间
      socket.join(`conversation_${conversation_id}`);
      
      socket.emit('joinedConversation', {
        code: 0,
        data: { conversation_id },
        msg: '已加入会话'
      });

      console.log(`用户 ${socket.userId} 加入会话 ${conversation_id}`);
    } catch (error) {
      console.error('加入会话失败:', error);
      socket.emit('error', {
        msg: error.message || '加入会话失败'
      });
    }
  }

  // 离开会话房间
  async leaveConversation() {
    const { ctx } = this;
    const { socket } = ctx;
    const { conversation_id } = ctx.args[0] || {};

    try {
      if (!conversation_id) {
        socket.emit('error', { msg: '会话ID不能为空' });
        return;
      }

      // 离开房间
      socket.leave(`conversation_${conversation_id}`);
      
      socket.emit('leftConversation', {
        code: 0,
        data: { conversation_id },
        msg: '已离开会话'
      });

      console.log(`用户 ${socket.userId} 离开会话 ${conversation_id}`);
    } catch (error) {
      console.error('离开会话失败:', error);
      socket.emit('error', {
        msg: error.message || '离开会话失败'
      });
    }
  }

  // 标记消息已读
  async markAsRead() {
    const { ctx, app } = this;
    const { socket } = ctx;
    const { message_ids, sender_id } = ctx.args[0] || {};

    try {
      if (!message_ids || !Array.isArray(message_ids)) {
        socket.emit('error', { msg: '消息ID列表不能为空' });
        return;
      }

      // 标记已读
      await ctx.service.message.markAsRead(message_ids, socket.userId);

      // 通知发送者消息已读
      if (sender_id) {
        const senderSocket = app.io.userSockets.get(parseInt(sender_id));
        if (senderSocket) {
          senderSocket.emit('messagesRead', {
            code: 0,
            data: { message_ids, reader_id: socket.userId },
            msg: '对方已读消息'
          });
        }
      }

      socket.emit('markedAsRead', {
        code: 0,
        data: { message_ids },
        msg: '已标记为已读'
      });
    } catch (error) {
      console.error('标记已读失败:', error);
      socket.emit('error', {
        msg: error.message || '标记已读失败'
      });
    }
  }

  // 正在输入状态
  async typing() {
    const { ctx, app } = this;
    const { socket } = ctx;
    const { receiver_id, is_typing } = ctx.args[0] || {};

    try {
      if (!receiver_id) {
        return;
      }

      // 通知对方正在输入
      const receiverSocket = app.io.userSockets.get(parseInt(receiver_id));
      if (receiverSocket) {
        receiverSocket.emit('userTyping', {
          code: 0,
          data: {
            user_id: socket.userId,
            is_typing: is_typing !== false
          }
        });
      }
    } catch (error) {
      console.error('发送输入状态失败:', error);
    }
  }
}

module.exports = ChatController;

